<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="./source/css/reset-1.3.3.css">
  <link rel="stylesheet" href="./source/css/demo.css">
</head>
<body>
  <div class="plugin-wrap">
    <div class="length-info">已添加<span class="picture-num">0</span>张图片</div>
    <div class="imgWrap">
      <div class="addBtn">
        <input id="upload" type="file" multiple="multiple">
      </div>
    </div>
  </div>
</body>
<script>
  var uploadBtn = document.querySelector('#upload')
  var addBtn = document.querySelector('.addBtn')
  var wrap = document.querySelector('.imgWrap')
  uploadBtn.addEventListener('change', upfile, false)
  
  var formData = new FormData()

  function upfile() {

    var files = this.files
    var filelength = files.length
    
    if(filelength) {
      
      for (var i = 0; i < filelength; i++) {
        var file = files[i]
        
        // 将二进制文件添加到fomrData
        formData.append(file.name,file)
        
        // fileReader对象读取文件内容
        var reader = new FileReader()
               
        // FileReader读取的内容可以是file文件或者blob格式数据
        reader.readAsDataURL(file)
        // readDataURL返回URL格式的字符串
        reader.onload = function (result) {

          var preview = document.createElement('div')
          wrap.insertBefore (preview,addBtn)
          preview.classList.add('preview')
          var img = document.createElement('img')
          preview.appendChild(img)
          var del = document.createElement('span')
          del.classList.add('delete')
          preview.appendChild(del)

          var result = result.target.result

          img.src = result
          img.name = file.name

          // 判断当前图片数量，达到最大上传数量则隐藏上传按钮
          var previewsImg = document.getElementsByClassName('preview')
          var pictureNum = previewsImg.length

          document.querySelector('.picture-num').textContent = pictureNum

          if(pictureNum >= 6) {

            addBtn.style.display = 'none'
          }

          // 删除图片
          del.addEventListener('click',function(e){

            // 将当前图片从formData删除  
            var deleteFile = e.target.previousSibling.name

            formData.delete(deleteFile)


            for (var key of formData.keys()) {
              console.log(key)
            }
            e.target.parentElement.parentElement.removeChild(e.target.parentElement)

            // 图片数少于6张，则显示上传按钮
            var imgs = document.getElementsByClassName('preview').length
            document.querySelector('.picture-num').textContent = imgs
            
            if(imgs < 6) {
              addBtn.style.display = 'block'
            }

          })
        }
      }


    }
  }

    
</script>
</html>